/** biome-ignore-all lint/correctness/noNestedComponentDefinitions: ignore */
import { SyntaxHighlighter } from "@renderer/components/business/syntax-highlighter";
import { Button } from "@renderer/components/ui/base/button";
import {
  Disclosure,
  DisclosurePanel,
  DisclosureTrigger,
} from "@renderer/components/ui/base/disclosure";
import { FieldGroup, Input, Label } from "@renderer/components/ui/base/field";
import { Link } from "@renderer/components/ui/base/link";
import { Modal } from "@renderer/components/ui/base/modal";
import { Select } from "@renderer/components/ui/base/select";
import { Switch } from "@renderer/components/ui/base/switch";
import { TextField } from "@renderer/components/ui/base/text-field";
import { Tooltip } from "@renderer/components/ui/base/tooltip";
import { cn } from "@renderer/lib/utils";
import { useMcpServers, useMcpToolsByServerId } from "@renderer/queries";
import logger from "@shared/logger/renderer-logger";
import type {
  CreateMcpServerData,
  McpServerType,
  McpTool,
} from "@shared/triplit/types";
import { EmojiPicker } from "frimousse";
import { ChevronLeft, RefreshCw, Trash2, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";

const { mcpService } = window.service;

interface KeyValuePair {
  key: string;
  value: string;
  id: string;
}

interface KeyValueInputProps {
  items: KeyValuePair[];
  setItems: (items: KeyValuePair[]) => void;
  nameLabel: string;
  addLabel: string;
  t: (key: string) => string;
}

const KeyValueInput = ({
  items,
  setItems,
  nameLabel,
  addLabel,
  t,
}: KeyValueInputProps) => {
  const addKeyValuePair = () => {
    setItems([
      ...items,
      { key: "", value: "", id: `item-${Date.now()}-${Math.random()}` },
    ]);
  };

  const updateKeyValuePair = (
    index: number,
    field: "key" | "value",
    value: string,
  ) => {
    const updated = [...items];
    updated[index][field] = value;
    setItems(updated);
  };

  const removeKeyValuePair = (index: number) => {
    setItems(items.filter((_, i) => i !== index));
  };

  return (
    <div className="flex flex-col gap-2">
      <div className="flex items-center justify-between">
        <Label className="text-fg">{nameLabel}</Label>
        <Link
          className="cursor-pointer text-primary no-underline hover:no-underline"
          intent="unstyled"
          onPress={addKeyValuePair}
        >
          {addLabel}
        </Link>
      </div>
      {items.map((item, index) => (
        <div key={item.id} className="flex items-center gap-2">
          <div className="flex-1">
            <TextField
              placeholder={
                nameLabel === t("form.advanced.headers.label")
                  ? t("form.advanced.headers.name-placeholder")
                  : t("form.advanced.env.name-placeholder")
              }
              value={item.key}
              onChange={(value) => updateKeyValuePair(index, "key", value)}
            >
              <FieldGroup className="bg-white dark:bg-[#121212]">
                <Input
                  placeholder={
                    nameLabel === t("form.advanced.headers.label")
                      ? t("form.advanced.headers.name-placeholder")
                      : t("form.advanced.env.name-placeholder")
                  }
                />
              </FieldGroup>
            </TextField>
          </div>
          <div className="flex-[2]">
            <TextField
              placeholder={
                nameLabel === t("form.advanced.headers.label")
                  ? t("form.advanced.headers.value-placeholder")
                  : t("form.advanced.env.value-placeholder")
              }
              value={item.value}
              onChange={(value) => updateKeyValuePair(index, "value", value)}
            >
              <FieldGroup className="bg-white dark:bg-[#121212]">
                <Input
                  placeholder={
                    nameLabel === t("form.advanced.headers.label")
                      ? t("form.advanced.headers.value-placeholder")
                      : t("form.advanced.env.value-placeholder")
                  }
                />
              </FieldGroup>
            </TextField>
          </div>
          <Button
            className="!size-8 !p-0 cursor-pointer text-muted-fg hover:text-fg"
            intent="plain"
            onPress={() => removeKeyValuePair(index)}
          >
            <X className="!size-4" />
          </Button>
        </div>
      ))}
    </div>
  );
};

export function McpAddServer() {
  const { t } = useTranslation("translation", {
    keyPrefix: "settings.mcp-settings.add-server",
  });

  const navigate = useNavigate();
  const location = useLocation();
  const { serverId } = useParams();
  const isEditMode = Boolean(serverId);
  const { data: servers = [] } = useMcpServers();

  // Find the server data if in edit mode
  const currentServer = isEditMode
    ? servers.find((s) => s.id === serverId)
    : null;

  // Form state
  const [name, setName] = useState("");
  const [type, setType] = useState<McpServerType>("streamableHTTP");
  const [icon, setIcon] = useState("");
  const [url, setUrl] = useState("");
  const [command, setCommand] = useState("");
  const [timeout, setTimeout] = useState(0);
  const [headers, setHeaders] = useState<KeyValuePair[]>([]);
  const [envVars, setEnvVars] = useState<KeyValuePair[]>([]);
  const [autoUseTools, setAutoUseTools] = useState(true);
  const [keepConnection, setKeepConnection] = useState(false);

  // Save state - track current server ID for new servers after save
  const [currentServerId, setCurrentServerId] = useState<string | null>(
    serverId || null,
  );

  // Track if we're in effective edit mode (either originally editing, or saved once in new mode)
  const isEffectiveEditMode = Boolean(serverId || currentServerId);

  // Loading states
  const [isSaving, setIsSaving] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [showValidationDialog, setShowValidationDialog] = useState(false);

  // Validation state - only show validation errors after user interaction
  const [hasAttemptedSave, setHasAttemptedSave] = useState(false);
  const [touchedFields, setTouchedFields] = useState<{
    name: boolean;
    url: boolean;
    command: boolean;
  }>({
    name: false,
    url: false,
    command: false,
  });
  const [validationState, setValidationState] = useState<{
    isLoading: boolean;
    success: boolean | null;
    error: string | null;
    toolCount?: number;
  }>({
    isLoading: false,
    success: null,
    error: null,
  });

  // Tab state
  const [activeTab, setActiveTab] = useState("tools");
  const [thumbStyle, setThumbStyle] = useState({});
  const tabItemsRef = useRef<(HTMLDivElement | null)[]>([]);
  const tabContainerRef = useRef<HTMLDivElement>(null);
  const [selectedTool, setSelectedTool] = useState<{
    name: string;
    description: string;
    parameters: unknown;
  } | null>(null);

  // Tab item ref setter
  const setTabItemRef = (index: number) => (el: HTMLDivElement | null) => {
    tabItemsRef.current[index] = el;
  };

  // Track if data has been loaded to prevent re-initialization
  const [dataLoaded, setDataLoaded] = useState(false);

  // Random emoji icons for MCP servers
  const mcpEmojis = [
    "🔧",
    "⚙️",
    "🛠️",
    "🔌",
    "⚡",
    "🤖",
    "💻",
    "🔗",
    "🌐",
    "📡",
    "🎯",
    "🚀",
    "💡",
    "🔥",
    "⭐",
  ];

  // Function to get random emoji
  const getRandomEmoji = () => {
    return mcpEmojis[Math.floor(Math.random() * mcpEmojis.length)];
  };

  // Check for import data from URL params
  const searchParams = new URLSearchParams(location.search);
  const isImportMode = searchParams.get("import") === "true";
  const importDataStr = searchParams.get("data");

  // Parse import data if available
  const importData = useMemo(() => {
    if (!isImportMode || !importDataStr) return null;
    try {
      return JSON.parse(importDataStr);
    } catch {
      return null;
    }
  }, [isImportMode, importDataStr]);

  // Ref for emoji picker container to handle outside clicks
  const emojiPickerRef = useRef<HTMLDivElement>(null);

  // Close emoji picker when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        emojiPickerRef.current &&
        !emojiPickerRef.current.contains(event.target as Node)
      ) {
        setShowEmojiPicker(false);
      }
    };

    if (showEmojiPicker) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [showEmojiPicker]);

  // Reset dataLoaded when serverId changes and set random icon for new servers
  // biome-ignore lint/correctness/useExhaustiveDependencies: Need serverId to reset state when switching servers
  useEffect(() => {
    setDataLoaded(false);
    // If this is a new server (not edit mode), set random icon
    if (!serverId && !dataLoaded) {
      setIcon(getRandomEmoji());
    }
  }, [serverId]);

  // Initialize random icon for new servers on first load
  // biome-ignore lint/correctness/useExhaustiveDependencies: getRandomEmoji is stable function and icon dependency would cause infinite loop
  useEffect(() => {
    if (!isEditMode && !icon) {
      setIcon(getRandomEmoji());
    }
  }, [isEditMode]);

  // Load server data in edit mode
  useEffect(() => {
    if (isEditMode && currentServer && serverId && !dataLoaded) {
      setName(currentServer.name || "");
      setType(currentServer.type || "streamableHTTP");
      setIcon(currentServer.icon || "");
      setUrl(currentServer.url || "");
      setCommand(currentServer.command || "");
      setTimeout(currentServer.advancedSettings?.timeout || 0);

      // Convert headers object to array
      const headersArray = currentServer.advancedSettings?.customHeaders
        ? Object.entries(currentServer.advancedSettings.customHeaders).map(
            ([key, value], index) => ({
              key,
              value: String(value),
              id: `header-${serverId}-${index}`,
            }),
          )
        : [];
      setHeaders(headersArray);

      // Convert env vars object to array
      const envVarsArray = currentServer.advancedSettings?.customEnvVars
        ? Object.entries(currentServer.advancedSettings.customEnvVars).map(
            ([key, value], index) => ({
              key,
              value: String(value),
              id: `env-${serverId}-${index}`,
            }),
          )
        : [];
      setEnvVars(envVarsArray);

      setAutoUseTools(currentServer.advancedSettings?.autoUseTool ?? true);
      setKeepConnection(
        currentServer.advancedSettings?.keepLongTaskConnection ?? false,
      );
      setDataLoaded(true);
    }
  }, [isEditMode, currentServer, serverId, dataLoaded]);

  // Load import data if available
  // biome-ignore lint/correctness/useExhaustiveDependencies: getRandomEmoji is stable function
  useEffect(() => {
    if (isImportMode && importData && !dataLoaded && !isEditMode) {
      setName(importData.name || "");
      setType(importData.type || "streamableHTTP");
      setUrl(importData.url || "");

      // Handle command and args combination for stdio
      if (importData.type === "stdio") {
        let fullCommand = importData.command || "";
        if (
          importData.args &&
          Array.isArray(importData.args) &&
          importData.args.length > 0
        ) {
          // Only add args if command exists and args array is not empty
          if (fullCommand) {
            fullCommand = `${fullCommand} ${importData.args.join(" ")}`;
          } else {
            // If no command but args exist, just use args
            fullCommand = importData.args.join(" ");
          }
        }
        setCommand(fullCommand.trim());
      } else {
        setCommand(importData.command || "");
      }

      // Handle environment variables (same for all types)
      if (importData.env) {
        const envArray = Object.entries(importData.env).map(
          ([key, value], index) => ({
            key,
            value: String(value),
            id: `import-env-${index}`,
          }),
        );
        setEnvVars(envArray);
      }

      // Set random icon if no icon provided in import data
      if (!importData.icon) {
        setIcon(getRandomEmoji());
      }

      setDataLoaded(true);

      // Clear the URL params to clean up the URL
      window.history.replaceState({}, "", location.pathname);
    }
  }, [isImportMode, importData, dataLoaded, isEditMode, location.pathname]);

  const typeOptions = [
    { id: "streamableHTTP", name: t("form.type.options.streamableHTTP") },
    { id: "stdio", name: t("form.type.options.stdio") },
    { id: "sse", name: t("form.type.options.sse") },
  ];

  const handleBack = () => {
    navigate("/settings/mcp-settings");
  };

  const handleDelete = () => {
    setShowDeleteDialog(true);
  };

  const handleConfirmDelete = async () => {
    const serverIdToDelete = serverId || currentServerId;
    if (!isEffectiveEditMode || !serverIdToDelete) return;

    try {
      await mcpService.deleteMcpServer(serverIdToDelete);
      navigate("/settings/mcp-settings");
    } catch (err) {
      logger.error("Failed to delete MCP server", {
        error: err,
        serverId: serverIdToDelete,
      });
    } finally {
      setShowDeleteDialog(false);
    }
  };

  const validateConnection = async (): Promise<boolean> => {
    setValidationState({ isLoading: true, success: null, error: null });
    setShowValidationDialog(true);

    try {
      // Filter out empty key-value pairs
      const validHeaders = headers.filter(
        (h) => h.key.trim() && h.value.trim(),
      );
      const validEnvVars = envVars.filter(
        (e) => e.key.trim() && e.value.trim(),
      );

      const serverData: CreateMcpServerData = {
        name,
        description: "",
        type,
        url: type === "stdio" ? "" : url,
        command: type === "stdio" ? command : "",
        icon,
        enabled: true,
        order: 0,
        advancedSettings: {
          timeout,
          customHeaders: Object.fromEntries(
            validHeaders.map(({ key, value }) => [key, value]),
          ),
          customEnvVars: Object.fromEntries(
            validEnvVars.map(({ key, value }) => [key, value]),
          ),
          autoUseTool: autoUseTools,
          keepLongTaskConnection: keepConnection,
        },
      };

      const result = await mcpService.testMcpServerConnection(serverData);

      if (result.success) {
        setValidationState({
          isLoading: false,
          success: true,
          error: null,
          toolCount: result.tools?.length || 0,
        });
        return true;
      } else {
        setValidationState({
          isLoading: false,
          success: false,
          error: result.errorMessage || "Unknown error",
        });
        return false;
      }
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : "Unknown error occurred";
      logger.error("Failed to validate MCP server connection", { error: err });
      setValidationState({
        isLoading: false,
        success: false,
        error: errorMessage,
      });
      return false;
    }
  };

  const performSave = async () => {
    try {
      setIsSaving(true);

      // Filter out empty key-value pairs
      const validHeaders = headers.filter(
        (h) => h.key.trim() && h.value.trim(),
      );
      const validEnvVars = envVars.filter(
        (e) => e.key.trim() && e.value.trim(),
      );

      const serverData: CreateMcpServerData = {
        name,
        description: "",
        type,
        url: type === "stdio" ? "" : url,
        command: type === "stdio" ? command : "",
        icon,
        enabled: true,
        order: 0,
        advancedSettings: {
          timeout,
          customHeaders: Object.fromEntries(
            validHeaders.map(({ key, value }) => [key, value]),
          ),
          customEnvVars: Object.fromEntries(
            validEnvVars.map(({ key, value }) => [key, value]),
          ),
          autoUseTool: autoUseTools,
          keepLongTaskConnection: keepConnection,
        },
      };

      let targetServerId: string;

      if (isEffectiveEditMode) {
        // Update existing server (either original edit mode or after first save in new mode)
        const serverIdToUpdate = serverId || currentServerId;
        if (!serverIdToUpdate) {
          throw new Error("No server ID available for update");
        }
        await mcpService.updateMcpServer(serverIdToUpdate, serverData);
        targetServerId = serverIdToUpdate;
        logger.info("MCP server updated", {
          id: targetServerId,
          name,
        });
      } else {
        // Create new server (only for first save in new mode)
        const newServer = await mcpService.insertMcpServer(serverData);
        targetServerId = newServer.id;
        // Update current server ID state for new servers
        setCurrentServerId(targetServerId);
        logger.info("New MCP server created", {
          id: targetServerId,
          name: newServer.name,
        });
      }

      // After successful save, connect to the server and sync its tools
      try {
        logger.info("Connecting to MCP server after save", {
          serverId: targetServerId,
          name,
        });

        // Connect to the server (this will add it to the global client map)
        await mcpService.connectToMcpServerManual(targetServerId);

        logger.info("MCP server connected successfully after save", {
          serverId: targetServerId,
          name,
        });

        // Small delay to ensure connection is fully established
        await new Promise<void>((resolve) =>
          globalThis.setTimeout(resolve, 500),
        );

        // Now refresh all tools (which will include the newly connected server)
        await mcpService.refreshAllTools();

        logger.info("Tools refreshed after server connection", {
          serverId: targetServerId,
          name,
        });
      } catch (connectionErr) {
        logger.warn("Failed to connect or sync tools after server save", {
          error: connectionErr,
          serverId: targetServerId,
          name,
        });
        // Don't fail the save operation if connection/tool sync fails
        // The server is saved successfully, user can manually refresh later
      }

      // Show success message but don't navigate away - let user decide when to go back
      toast.success(
        isEffectiveEditMode ? t("update-success") : t("save-success"),
      );
    } catch (err) {
      logger.error("Failed to save MCP server", {
        error: err,
        isEditMode,
        name,
      });
      toast.error("Failed to save MCP server");
    } finally {
      setIsSaving(false);
    }
  };

  const handleSave = async () => {
    // Mark that user has attempted to save
    setHasAttemptedSave(true);

    // Validate required fields first
    if (!name.trim()) {
      toast.error(t("form.name.required-error"));
      return;
    }

    if (type === "stdio") {
      if (!command.trim()) {
        toast.error(t("form.command.required-error"));
        return;
      }
    } else {
      if (!url.trim()) {
        toast.error(t("form.url.required-error"));
        return;
      }
    }

    // Always validate connection before saving, regardless of edit mode
    const isValid = await validateConnection();
    if (isValid) {
      setShowValidationDialog(false);
      await performSave();
    }
    // If validation fails, keep the dialog open for user to decide
  };

  // Helper function to determine if validation should be shown
  const shouldShowValidation = (fieldName: "name" | "url" | "command") => {
    return hasAttemptedSave || touchedFields[fieldName];
  };

  // Handle field blur to mark as touched
  const handleFieldBlur = (fieldName: "name" | "url" | "command") => {
    setTouchedFields((prev) => ({
      ...prev,
      [fieldName]: true,
    }));
  };

  // Get real MCP tools data for this server
  const { data: mcpTools = [] } = useMcpToolsByServerId(currentServerId || "", {
    enabled: Boolean(currentServerId),
  });

  // Refresh tools handler
  const handleRefreshTools = async () => {
    if (!currentServerId || isRefreshing) return;

    setIsRefreshing(true);
    try {
      await mcpService.refreshAllTools();
      toast.success(t("refresh.success"));
    } catch (error) {
      logger.error("Failed to refresh tools:", { error });
      toast.error(t("refresh.error"));
    } finally {
      setIsRefreshing(false);
    }
  };

  const tabData = {
    tools: {
      count: mcpTools.length,
      items: [...mcpTools].sort((a, b) => a.name.localeCompare(b.name)),
    },
    prompts: { count: 0, items: [] },
    resources: { count: 0, items: [] },
  };

  const tabOptions = useMemo(
    () => [
      { id: "tools", label: t("tabs.tools"), count: tabData.tools.count },
      { id: "prompts", label: t("tabs.prompts"), count: tabData.prompts.count },
      {
        id: "resources",
        label: t("tabs.resources"),
        count: tabData.resources.count,
      },
    ],
    [t, tabData.tools.count, tabData.prompts.count, tabData.resources.count],
  );

  // Update thumb position when activeTab changes
  useEffect(() => {
    const currentIndex = tabOptions.findIndex(
      (option) => option.id === activeTab,
    );
    if (
      currentIndex === -1 ||
      !tabItemsRef.current[currentIndex] ||
      !tabContainerRef.current
    ) {
      return;
    }

    const item = tabItemsRef.current[currentIndex];
    const container = tabContainerRef.current;
    const containerRect = container.getBoundingClientRect();
    const itemRect = item.getBoundingClientRect();

    setThumbStyle({
      left: `${itemRect.left - containerRect.left}px`,
      width: `${itemRect.width}px`,
    });
  }, [activeTab, tabOptions]);

  const renderTabContent = () => {
    const currentData = tabData[activeTab as keyof typeof tabData];

    if (activeTab === "tools") {
      return (
        <div className="space-y-2">
          {currentData.items.length > 0 ? (
            currentData.items.map((tool: McpTool) => (
              <button
                key={tool.name}
                type="button"
                className="flex w-full cursor-pointer items-center rounded-[10px] bg-white px-3.5 py-3 hover:bg-[#F9F9F9] dark:bg-bg dark:hover:bg-[#2D2D2D]"
                onClick={() =>
                  setSelectedTool({
                    name: tool.name,
                    description: tool.description || "",
                    parameters: tool.parameters,
                  })
                }
              >
                <span className="text-setting-fg text-sm">{tool.name}</span>
              </button>
            ))
          ) : (
            <div className="py-4 text-center text-muted-fg">
              {t("tabs.empty.tools")}
            </div>
          )}
        </div>
      );
    }

    // Placeholder for other tabs
    return (
      <div className="py-4 text-center text-muted-fg">
        {activeTab === "prompts"
          ? t("tabs.empty.prompts")
          : t("tabs.empty.resources")}
      </div>
    );
  };

  return (
    <div className="flex h-full w-full flex-col">
      <div className="flex flex-col gap-6 pb-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <Button
            className="h-8 gap-1 px-2"
            intent="outline"
            onPress={handleBack}
          >
            <ChevronLeft className="h-4 w-4" />
            <span>{t("back-button")}</span>
          </Button>

          <div className="flex gap-2">
            {isEffectiveEditMode && (
              <Button
                className="!inset-ring-[#D82525] h-8 text-[#D82525] [--btn-outline:#D82525] hover:bg-[#D82525] hover:text-white"
                intent="outline"
                onPress={handleDelete}
              >
                <Trash2 className="h-4 w-4" />
                <span>{t("delete-button")}</span>
              </Button>
            )}
            <Button className="h-8" onPress={handleSave} isPending={isSaving}>
              <span>{isSaving ? t("saving") : t("save-button")}</span>
            </Button>
          </div>
        </div>

        {/* Form */}
        <div className="flex flex-col gap-4">
          {/* 名称 */}
          <TextField
            label={t("form.name.label")}
            placeholder={t("form.name.placeholder")}
            value={name}
            onChange={setName}
          >
            <Label>
              {t("form.name.label")}
              <span className="ml-1 text-red-500">*</span>
            </Label>
            <FieldGroup
              className={`bg-[#F5F5F5] dark:bg-[#1A1A1A] ${
                shouldShowValidation("name") && !name.trim()
                  ? "!inset-ring-red-300 dark:!inset-ring-red-500"
                  : ""
              }`}
            >
              <Input
                placeholder={t("form.name.placeholder")}
                onBlur={() => handleFieldBlur("name")}
              />
            </FieldGroup>
          </TextField>

          {/* 类型 */}
          <div className="flex flex-col gap-2">
            <Label className="text-fg">{t("form.type.label")}</Label>
            <Select
              className="rounded-[10px] bg-[#F5F5F5] dark:bg-[#1A1A1A]"
              selectedKey={type}
              onSelectionChange={(key) => setType(key as McpServerType)}
            >
              <Select.Trigger />
              <Select.List>
                {typeOptions.map((option) => (
                  <Select.Option key={option.id} id={option.id}>
                    {option.name}
                  </Select.Option>
                ))}
              </Select.List>
            </Select>
          </div>

          {/* 图标 */}
          <div className="flex flex-col gap-2">
            <Label className="text-fg">{t("form.icon.label")}</Label>
            <div className="relative inline-block w-fit">
              <Button
                className="h-11 w-11 justify-center bg-[#F5F5F5] p-0 dark:bg-[#1A1A1A]"
                intent="plain"
                onPress={() => setShowEmojiPicker(!showEmojiPicker)}
              >
                {icon ? (
                  <span className="text-xl">{icon}</span>
                ) : (
                  <div className="h-6 w-6 rounded bg-muted" />
                )}
              </Button>

              {showEmojiPicker && (
                <div
                  ref={emojiPickerRef}
                  className="absolute top-full left-0 z-50 mt-1"
                >
                  <EmojiPicker.Root className="isolate flex h-[368px] w-fit flex-col rounded-lg border border-border bg-white shadow-lg dark:bg-neutral-900">
                    <EmojiPicker.Search className="z-10 mx-2 mt-2 appearance-none rounded-md bg-neutral-100 px-2.5 py-2 text-sm dark:bg-neutral-800" />
                    <EmojiPicker.Viewport className="relative flex-1 outline-hidden">
                      <EmojiPicker.Loading className="absolute inset-0 flex items-center justify-center text-neutral-400 text-sm dark:text-neutral-500">
                        {t("form.icon.loading")}
                      </EmojiPicker.Loading>
                      <EmojiPicker.Empty className="absolute inset-0 flex items-center justify-center text-neutral-400 text-sm dark:text-neutral-500">
                        {t("form.icon.no-emoji")}
                      </EmojiPicker.Empty>
                      <EmojiPicker.List
                        className="select-none pb-1.5"
                        components={{
                          CategoryHeader: ({ category, ...props }) => (
                            <div
                              className="bg-white px-3 pt-3 pb-1.5 font-medium text-neutral-600 text-xs dark:bg-neutral-900 dark:text-neutral-400"
                              {...props}
                            >
                              {category.label}
                            </div>
                          ),
                          Row: ({ children, ...props }) => (
                            <div className="scroll-my-1.5 px-1.5" {...props}>
                              {children}
                            </div>
                          ),
                          Emoji: ({ emoji, ...props }) => (
                            <button
                              className="flex size-8 items-center justify-center rounded-md text-lg data-[active]:bg-neutral-100 dark:data-[active]:bg-neutral-800"
                              {...props}
                              onClick={() => {
                                setIcon(emoji.emoji);
                                setShowEmojiPicker(false);
                              }}
                            >
                              {emoji.emoji}
                            </button>
                          ),
                        }}
                      />
                    </EmojiPicker.Viewport>
                  </EmojiPicker.Root>
                </div>
              )}
            </div>
          </div>

          {/* URL - only shown for non-stdio types */}
          {type !== "stdio" && (
            <TextField
              label={t("form.url.label")}
              placeholder={t("form.url.placeholder")}
              value={url}
              onChange={setUrl}
            >
              <Label>
                {t("form.url.label")}
                <span className="ml-1 text-red-500">*</span>
              </Label>
              <FieldGroup
                className={`bg-[#F5F5F5] dark:bg-[#1A1A1A] ${
                  shouldShowValidation("url") && !url.trim()
                    ? "!inset-ring-red-300 dark:!inset-ring-red-500"
                    : ""
                }`}
              >
                <Input
                  placeholder={t("form.url.placeholder")}
                  onBlur={() => handleFieldBlur("url")}
                />
              </FieldGroup>
            </TextField>
          )}

          {/* Command field - only shown for stdio type */}
          {type === "stdio" && (
            <TextField
              label={t("form.command.label")}
              placeholder={t("form.command.placeholder")}
              value={command}
              onChange={setCommand}
            >
              <Label>
                {t("form.command.label")}
                <span className="ml-1 text-red-500">*</span>
              </Label>
              <FieldGroup
                className={`bg-[#F5F5F5] dark:bg-[#1A1A1A] ${
                  shouldShowValidation("command") && !command.trim()
                    ? "!inset-ring-red-300 dark:!inset-ring-red-500"
                    : ""
                }`}
              >
                <Input
                  placeholder={t("form.command.placeholder")}
                  onBlur={() => handleFieldBlur("command")}
                />
              </FieldGroup>
            </TextField>
          )}

          {/* 高级设置 */}
          <Disclosure className="border-none">
            <DisclosureTrigger className="flex w-full items-center justify-between rounded-lg bg-setting px-3 py-2 text-left">
              <span className="font-medium">{t("form.advanced.title")}</span>
            </DisclosureTrigger>
            <DisclosurePanel className="rounded-lg bg-setting group-data-[expanded=true]/disclosure:mt-2 group-data-[expanded=true]/disclosure:p-4">
              <div className="space-y-4">
                {/* 超时 */}
                <TextField
                  label={t("form.advanced.timeout.label")}
                  type="number"
                  value={timeout.toString()}
                  onChange={(value) => setTimeout(Number(value) || 0)}
                >
                  <Label>{t("form.advanced.timeout.label")}</Label>
                  <FieldGroup className="bg-white dark:bg-[#121212]">
                    <Input className="text-fg" type="number" />
                  </FieldGroup>
                </TextField>

                {/* 自定义请求头 - 只在 sse 和 streamableHTTP 类型时显示 */}
                {(type === "sse" || type === "streamableHTTP") && (
                  <KeyValueInput
                    items={headers}
                    setItems={setHeaders}
                    nameLabel={t("form.advanced.headers.label")}
                    addLabel={t("form.advanced.headers.add-button")}
                    t={t}
                  />
                )}

                {/* 环境变量 - 只在 stdio 类型时显示 */}
                {type === "stdio" && (
                  <KeyValueInput
                    items={envVars}
                    setItems={setEnvVars}
                    nameLabel={t("form.advanced.env.label")}
                    addLabel={t("form.advanced.env.add-button")}
                    t={t}
                  />
                )}

                {/* 其他设置 */}
                <div className="flex flex-col gap-2">
                  <Switch
                    className="h-11 w-full rounded-[10px] bg-white px-3.5 py-2.5 dark:bg-[#121212]"
                    isSelected={autoUseTools}
                    onChange={setAutoUseTools}
                  >
                    <Label className="self-center text-fg">
                      {t("form.advanced.other.auto-use-tools")}
                    </Label>
                  </Switch>

                  <Switch
                    className="h-11 w-full rounded-[10px] bg-white px-3.5 py-2.5 dark:bg-[#121212]"
                    isSelected={keepConnection}
                    onChange={setKeepConnection}
                  >
                    <Label className="self-center text-fg">
                      {t("form.advanced.other.keep-connection")}
                    </Label>
                  </Switch>
                </div>
              </div>
            </DisclosurePanel>
          </Disclosure>
        </div>

        {/* Tabs Section */}
        <div className="flex flex-col gap-4">
          {/* Tab Headers with Refresh Button */}
          <div className="flex items-center gap-4">
            <div
              ref={tabContainerRef}
              className="relative flex h-11 flex-1 items-center rounded-[10px] bg-setting px-2"
            >
              {Object.hasOwn(thumbStyle, "left") && (
                <div
                  className="absolute z-2 h-[32px] rounded-md bg-accent transition-all duration-400 ease-out"
                  style={thumbStyle}
                />
              )}

              <div className="flex w-full gap-2">
                {tabOptions.map((tab, index) => (
                  <div
                    key={tab.id}
                    ref={setTabItemRef(index)}
                    className={cn(
                      "relative z-2 flex h-[32px] flex-1 cursor-pointer items-center justify-center gap-1 rounded-md text-sm",
                      activeTab === tab.id
                        ? "text-accent-fg"
                        : "z-1 text-secondary-fg hover:bg-hover-primary",
                    )}
                    onMouseDown={() => setActiveTab(tab.id)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") {
                        setActiveTab(tab.id);
                      }
                    }}
                    aria-checked={activeTab === tab.id}
                    role="switch"
                    tabIndex={0}
                  >
                    <span>{tab.label}</span>
                    {tab.count > 0 && (
                      <span className="rounded-full bg-muted px-2 py-0.5 text-xs">
                        {tab.count}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            </div>

            {/* Refresh Button */}
            <Button
              className="h-11 w-11 rounded-[10px] p-0"
              intent="outline"
              onPress={handleRefreshTools}
              isDisabled={!currentServerId || isRefreshing}
            >
              <RefreshCw
                className={cn("h-4 w-4", { "animate-spin": isRefreshing })}
              />
            </Button>
          </div>

          {/* Tab Content */}
          <div className="min-h-[200px]">{renderTabContent()}</div>
        </div>
      </div>

      {/* Tool Details Modal */}
      <Modal isOpen={!!selectedTool} onOpenChange={() => setSelectedTool(null)}>
        <Modal.Content size="4xl">
          {() => (
            <>
              <Modal.Header className="hidden">
                <Modal.Title></Modal.Title>
              </Modal.Header>
              <Modal.Body className="px-6 py-4">
                <h3 className="text-setting-fg text-sm">
                  {selectedTool?.name}
                </h3>
                <div className="space-y-4">
                  {selectedTool?.description && (
                    <div>
                      <Tooltip>
                        <Tooltip.Trigger>
                          <p className="line-clamp-2 cursor-help text-muted-fg">
                            {selectedTool.description}
                          </p>
                        </Tooltip.Trigger>
                        <Tooltip.Content>
                          <p className="max-w-xs whitespace-pre-wrap">
                            {selectedTool.description}
                          </p>
                        </Tooltip.Content>
                      </Tooltip>
                    </div>
                  )}
                  <div>
                    <div className="h-[400px] overflow-auto rounded-lg border border-border bg-background">
                      <SyntaxHighlighter
                        title={t("tabs.tool-modal.parameters")}
                        language="json"
                        showLineNumbers={false}
                        className="text-sm"
                      >
                        {JSON.stringify(
                          selectedTool?.parameters || {},
                          null,
                          2,
                        )}
                      </SyntaxHighlighter>
                    </div>
                  </div>
                </div>
              </Modal.Body>
            </>
          )}
        </Modal.Content>
      </Modal>

      {/* Connection Validation Dialog */}
      <Modal
        isOpen={showValidationDialog}
        onOpenChange={setShowValidationDialog}
      >
        <Modal.Content size="lg">
          {() => (
            <>
              <Modal.Header className="border-b-0 pb-4">
                <Modal.Title className="text-center font-medium text-lg">
                  {t("validation.dialog.title")}
                </Modal.Title>
              </Modal.Header>
              <Modal.Body className="px-6 pb-2">
                <div className="flex flex-col items-center space-y-4">
                  {validationState.isLoading && (
                    <>
                      <div className="relative">
                        <div className="h-12 w-12 animate-spin rounded-full border-3 border-blue-200 border-t-blue-500 dark:border-blue-800 dark:border-t-blue-400" />
                      </div>
                      <div className="space-y-2 text-center">
                        <p className="font-medium text-base text-fg">
                          {t("validation.testing-connection")}
                        </p>
                        <p className="text-muted-fg text-sm">
                          {t("validation.dialog.testing-message")}
                        </p>
                      </div>
                    </>
                  )}

                  {validationState.success === true && (
                    <>
                      <div className="relative">
                        <div className="flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/30">
                          <svg
                            className="h-6 w-6 text-green-600 dark:text-green-400"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                            role="img"
                            aria-label="Success"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M5 13l4 4L19 7"
                            />
                          </svg>
                        </div>
                      </div>
                      <div className="space-y-2 text-center">
                        <p className="font-medium text-base text-green-700 dark:text-green-400">
                          {t("validation.connection-success")}
                        </p>
                        <p className="text-muted-fg text-sm">
                          {t("validation.dialog.success-message", {
                            count: validationState.toolCount || 0,
                          })}
                        </p>
                      </div>
                    </>
                  )}

                  {validationState.success === false && (
                    <>
                      <div className="relative">
                        <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/30">
                          <svg
                            className="h-6 w-6 text-red-600 dark:text-red-400"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                            role="img"
                            aria-label="Error"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
                            />
                          </svg>
                        </div>
                      </div>
                      <div className="space-y-2 text-center">
                        <p className="font-medium text-base text-red-700 dark:text-red-400">
                          {t("validation.connection-failed")}
                        </p>
                        <div className="max-w-sm">
                          <p className="break-words text-muted-fg text-sm">
                            {validationState.error}
                          </p>
                        </div>
                      </div>
                    </>
                  )}
                </div>
              </Modal.Body>
              <Modal.Footer className="border-t-0 px-6 pt-4 pb-6">
                <div className="flex w-full justify-center space-x-3">
                  {validationState.isLoading && (
                    <Modal.Close isDisabled>
                      {t("validation.dialog.close")}
                    </Modal.Close>
                  )}

                  {validationState.success === true && (
                    <Modal.Close>{t("validation.dialog.close")}</Modal.Close>
                  )}

                  {validationState.success === false && (
                    <>
                      <Button
                        intent="outline"
                        onPress={() => validateConnection()}
                      >
                        {t("validation.dialog.retry")}
                      </Button>
                      <Button
                        intent="danger"
                        onPress={async () => {
                          setShowValidationDialog(false);
                          await performSave();
                        }}
                      >
                        {t("validation.dialog.save-anyway")}
                      </Button>
                      <Modal.Close>{t("validation.dialog.close")}</Modal.Close>
                    </>
                  )}
                </div>
              </Modal.Footer>
            </>
          )}
        </Modal.Content>
      </Modal>

      {/* Delete Confirmation Dialog */}
      <Modal isOpen={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <Modal.Content>
          {({ close }) => (
            <>
              <Modal.Header>
                <Modal.Title>{t("delete-dialog.title")}</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                <div className="space-y-3">
                  <p>
                    {t("delete-dialog.message", {
                      name: currentServer?.name || serverId,
                    })}
                  </p>
                  <p className="text-muted-fg text-sm">
                    {t("delete-dialog.warning")}
                  </p>
                </div>
              </Modal.Body>
              <Modal.Footer>
                <Modal.Close>{t("delete-dialog.cancel")}</Modal.Close>
                <Button
                  intent="danger"
                  onPress={async () => {
                    await handleConfirmDelete();
                    close();
                  }}
                >
                  {t("delete-dialog.confirm")}
                </Button>
              </Modal.Footer>
            </>
          )}
        </Modal.Content>
      </Modal>
    </div>
  );
}
